package com.bl.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {

    public static final String SECRET = "!@#$(*&%zel*^%$##@(wfy)@#!";

    //获取token
    public static <T> String getToken(T t) throws UnsupportedEncodingException {

        Map<String,Object> map = new HashMap<>();
        map.put("alg","HS256");
        map.put("type","JWT");

        //获取JWT令牌构建器
        JWTCreator.Builder builder = JWT.create();

        //令牌头部信息
        builder.withHeader(map);

        Class<?> clazz = t.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            Class<?> type = field.getType();
            if(type == String.class && !"password".equals(field.getName())){
                String fieldName = field.getName();
                char[] chars = fieldName.toCharArray();
                chars[0] = Character.toUpperCase(chars[0]);
                fieldName = new String(chars);
                String methodName = "get" + fieldName;
                try {
                    Method method = clazz.getMethod(methodName);
                    Object f = method.invoke(t);

                    //令牌的负载信息
                    builder.withClaim(fieldName,f.toString());
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        //令牌的过期时间
        Date date = new Date(System.currentTimeMillis() + 30 * 60 * 10000);
        builder.withExpiresAt(date);
        //令牌的签名信息
        String token = builder.sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    //验证token是否合法
    public static boolean verify(String token){
        try {
            JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
